package com.cjstudio.feetgesture;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public abstract class MyShakeDetectionService {
	
	protected Context mContext;
	public MyShakeDetectionService(Context mContext) {
		this.mContext = mContext;
	}
	
	public void startShakeDetection() {
		mSensorManager = (SensorManager)mContext.getSystemService(Context.SENSOR_SERVICE);
		mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
	}
	public void stopShakeDetection() {
		if(mSensorManager != null) {
			mSensorManager.unregisterListener(mSensorListener);
		}
	}
	
	static final float mShakeThreshold = 1.5f;
	
	private SensorManager mSensorManager;
	static float mAccel = 0.00f; // acceleration apart from gravity
	static float mAccelCurrent = SensorManager.GRAVITY_EARTH; // current acceleration including gravity
	static float mAccelLast = SensorManager.GRAVITY_EARTH; // last acceleration including gravity
	
	private final SensorEventListener mSensorListener = new SensorEventListener() {
			@Override
			public void onSensorChanged(SensorEvent se) {
				float x = se.values[0];
				float y = se.values[1];
				float z = se.values[2];
	
				mAccelLast = mAccelCurrent;
				mAccelCurrent = (float) Math.sqrt((x*x + y*y + z*z));
				float delta = mAccelCurrent - mAccelLast;
				mAccel = mAccel * 0.9f + delta; // perform low-cut filter
	    
		        if(mAccel > mShakeThreshold) {
		    			if(mAccel > mShakeThreshold) {
		    				onShakeDetected();
		    			}
		        }
	        
			}
	
			@Override
			public void onAccuracyChanged(Sensor sensor, int accuracy) { }
	};
	
	public abstract void onShakeDetected();
}
